package org.scboy.rbac.controller;

import org.scboy.common.cache.SystemConfig;
import org.scboy.common.request.Result;
import org.scboy.rbac.service.LoginSessionService;
import org.scboy.rbac.service.UserAccountService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.rbac.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("rbac/login")
public class LoginController {

	@Autowired
	LoginSessionService loginSessionService;

	@Autowired
	UserAccountService accountService;

	@Autowired
	SystemConfig config;
	
	/**
	 * 登录页面
	 * @return
	 */
	@GetMapping("init")
	public Result init(HttpServletRequest request){
		Model model=Model.create();
		model.add("LOGIN_NAME",config.getConfig("LOGIN_NAME"));
		model.add("PASSWORD_NAME",config.getConfig("PASSWORD_NAME"));
		model.add("CHECK_NAME",config.getConfig("CHECK_NAME"));
		model.add("CODE_NAME",config.getConfig("CODE_NAME"));
		return Result.Success(model, 0L);
	}
	
	/**
	 * 用户登录
	 * @param request
	 * @return
	 */
	@PostMapping("submit")
	public Result submit(HttpServletRequest request,@RequestBody Model params){
		//用户登录帐号
		String login=params.getString(config.getConfig("LOGIN_NAME"));
		String loginType=params.getString("loginType");
		if(StrUtil.isEmpty(loginType)) {
			loginType="local";
		}
		//用户登录密码
		String password=params.getString(config.getConfig("PASSWORD_NAME"));
		
		//登录验证
		//记录cookie和session
		String ips="[客户端]=";
		if(request.getHeader("X-Forwarded-For")!=null){
			ips+=request.getHeader("X-Forwarded-For").replaceAll(",", "->");
		}
		if(request.getRemoteAddr()!=null){
			ips+="->"+request.getRemoteAddr();
		}
		ips+="=[服务端]";
		LoginUser loginUser=loginSessionService.login(login, password,loginType, request.getRemoteAddr(),ips);
		if(loginUser==null){
			return Result.Error("RBAC_LOGIN_ERROR");
		}else{
			return Result.Success(loginUser,"RBAC_LOGIN_SUCCESS");
		}
		
	}
	
	/**
	 * 用户登出
	 * @param request
	 * @return
	 */
	@GetMapping("loginOut")
	public Result loginOut(HttpServletRequest request) {
		String token=request.getHeader(config.getConfig("TOKEN_KEY"));
		if(loginSessionService.loginOut(token,1)){
			return Result.Success("RBAC_LOGIN_OUT_SUCCESS");
		}else{
			return Result.Error("RBAC_LOGIN_OUT_ERROR");
		}
	}
}
